package com.study_day01.controller;

import com.study_day01.entiry.LoginRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

@RestController
@RequestMapping("/api/auth")
public class AuthController {

    @Autowired
    private AuthenticationManager authenticationManager;


    @PostMapping("/login")
    public Boolean login(@RequestBody LoginRequest request) {
        if ("admin".equals(request.getUsername()) && "123456".equals(request.getPassword())) {
//            loadUserByUsername(request.getUsername());

            Authentication authenticate = authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(request.getUsername(), request.getPassword()));
            SecurityContextHolder.getContext().setAuthentication(authenticate);
            return true;
            // 登录成功，返回认证信息
        } else {
            // 登录失败，返回错误信息
            return false;
        }
    }

    @RequestMapping("/logout")
    public String logout(HttpServletRequest request) {
        // 使当前会话无效
        SecurityContextHolder.clearContext();
        // 使当前会话无效
        request.getSession().invalidate();
        return "redirect:/login";
    }


}
